package com.example.gramediamajalahmobile.search;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.example.gramediamajalahmobile.JSONParser;
import com.example.gramediamajalahmobile.R;
import com.example.gramediamajalahmobile.main.Detail;

public class ResultSearch extends ListActivity {

	private static final String AR_ID = "id";
	private static final String AR_TITLE = "title";

	ArrayList<HashMap<String, String>> daftar_cari = new ArrayList<HashMap<String, String>>();


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.listviewresult);

		Intent in = getIntent();
		String keywords = in.getStringExtra("keyword");
		Log.i("KEY", keywords);

		String link_url = "http://192.168.2.23/codeigniter-restserver-master/index.php/gom/search_by_title?title="
				+ keywords;

		JSONParser jParser = new JSONParser();
		JSONArray json = jParser.AmbilJson(link_url);

		try {
			for (int i = 0; i < json.length(); i++) {
				JSONObject ar = json.getJSONObject(i);

				String id_s= ar.getString(AR_ID);
				String title_s= ar.getString(AR_TITLE);

				HashMap<String, String> map = new HashMap<String, String>();

				map.put(AR_ID, id_s);
				map.put(AR_TITLE, title_s);

				daftar_cari.add(map);

			}
		} catch (JSONException e) {
			e.printStackTrace();

		}
		this.adapter_listview();
	}

	public void adapter_listview() {

		ListAdapter adapter = new SimpleAdapter(this, daftar_cari,
				R.layout.lv_by_title, new String[] { AR_ID, AR_TITLE },
				new int[] { R.id.id_search, R.id.title_search });

		setListAdapter(adapter);
		ListView lv = getListView();
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String kode = ((TextView) view.findViewById(R.id.id_search))
						.getText().toString();

				Intent in = new Intent(ResultSearch.this, Detail.class);
				in.putExtra(AR_ID, kode);
				startActivity(in);

			}
		});
	}

}